"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: system.py
@DateTime: 2025/07/05
@Docs: 系统相关模型 - 根据数据字典3.3设计
"""

from tortoise import fields

from app.models.base import BaseModel


class UserSettings(BaseModel):
    """用户配置模型 - 3.3.7 UserSettings 表"""

    theme = fields.CharField(max_length=20, default="light", description="主题设置")
    language = fields.CharField(max_length=10, default="zh-CN", description="语言设置")
    sidebar_collapsed = fields.BooleanField(default=False, description="侧边栏折叠")
    page_size = fields.IntField(default=20, description="每页显示数量")
    timezone = fields.CharField(max_length=50, default="Asia/Shanghai", description="时区设置")
    notification_email = fields.BooleanField(default=True, description="邮件通知")
    notification_sms = fields.BooleanField(default=False, description="短信通知")
    custom_settings = fields.JSONField(null=True, description="自定义配置")
    description = fields.TextField(null=True, description="描述")

    # 外键关系
    user = fields.ForeignKeyField("models.User", related_name="settings", description="关联用户")

    class Meta:  # type: ignore
        table = "sys_user_settings"
        table_description = "用户配置表"

    def __str__(self) -> str:
        return f"UserSettings(user_id={self.user_id})"  # type: ignore

    def to_dict(self, exclude_sensitive: bool = False) -> dict:
        """转换为字典"""
        data = super().to_dict(exclude_sensitive=exclude_sensitive)
        data.update(
            {
                "user_id": self.user_id,  # type: ignore
                "theme": self.theme,
                "language": self.language,
                "sidebar_collapsed": self.sidebar_collapsed,
                "page_size": self.page_size,
                "timezone": self.timezone,
                "notification_email": self.notification_email,
                "notification_sms": self.notification_sms,
                "custom_settings": self.custom_settings,
                "description": self.description,
            }
        )
        return data


class SystemConfig(BaseModel):
    """系统配置模型 - 3.3.8 SystemConfig 表"""

    key = fields.CharField(max_length=100, unique=True, description="配置键")
    value = fields.TextField(null=True, description="配置值")
    category = fields.CharField(max_length=50, description="配置分类", db_index=True)
    type = fields.CharField(max_length=20, description="数据类型")
    is_public = fields.BooleanField(default=False, description="是否公开")
    is_readonly = fields.BooleanField(default=False, description="是否只读")
    sort_order = fields.IntField(default=0, description="排序", db_index=True)
    description = fields.TextField(null=True, description="描述")

    class Meta:  # type: ignore
        table = "sys_config"
        table_description = "系统配置表"

    def __str__(self) -> str:
        return f"SystemConfig(key={self.key})"

    def to_dict(self, exclude_sensitive: bool = False) -> dict:
        """转换为字典"""
        data = super().to_dict(exclude_sensitive=exclude_sensitive)
        data.update(
            {
                "key": self.key,
                "value": self.value,
                "category": self.category,
                "type": self.type,
                "is_public": self.is_public,
                "is_readonly": self.is_readonly,
                "sort_order": self.sort_order,
                "description": self.description,
            }
        )
        return data


class OperationLog(BaseModel):
    """操作日志模型 - 3.3.9 OperationLog 表"""

    module = fields.CharField(max_length=50, description="操作模块")
    action = fields.CharField(max_length=50, description="操作类型")
    resource_id = fields.CharField(max_length=100, null=True, description="资源ID")
    resource_type = fields.CharField(max_length=50, null=True, description="资源类型")
    method = fields.CharField(max_length=10, description="请求方法")
    path = fields.CharField(max_length=500, description="请求路径")
    ip_address = fields.CharField(max_length=45, description="IP地址", db_index=True)
    user_agent = fields.TextField(null=True, description="用户代理")
    request_data = fields.JSONField(null=True, description="请求数据")
    response_code = fields.IntField(description="响应码")
    response_time = fields.IntField(description="响应时间(ms)")
    description = fields.TextField(null=True, description="描述")

    # 外键关系
    user = fields.ForeignKeyField(
        "models.User", related_name="operation_logs", description="操作用户", on_delete=fields.SET_NULL, null=True
    )

    class Meta:  # type: ignore
        table = "sys_operation_log"
        table_description = "操作日志表"
        # 复合索引
        indexes = [
            ("module", "action"),
            ("resource_type", "resource_id"),
        ]

    def __str__(self) -> str:
        return f"OperationLog(user_id={self.user_id}, action={self.action})"  # type: ignore

    def to_dict(self, exclude_sensitive: bool = False) -> dict:
        """转换为字典"""
        data = super().to_dict(exclude_sensitive=exclude_sensitive)
        data.update(
            {
                "user_id": self.user_id,  # type: ignore
                "module": self.module,
                "action": self.action,
                "resource_id": self.resource_id,
                "resource_type": self.resource_type,
                "method": self.method,
                "path": self.path,
                "ip_address": self.ip_address,
                "user_agent": self.user_agent,
                "request_data": self.request_data,
                "response_code": self.response_code,
                "response_time": self.response_time,
                "description": self.description,
            }
        )
        return data


class LoginLog(BaseModel):
    """登录日志模型 - 3.3.10 LoginLog 表"""

    login_type = fields.CharField(max_length=20, description="登录类型", db_index=True)
    ip_address = fields.CharField(max_length=45, description="IP地址", db_index=True)
    location = fields.CharField(max_length=200, null=True, description="登录地点")
    device = fields.CharField(max_length=200, null=True, description="登录设备")
    user_agent = fields.TextField(null=True, description="用户代理")
    is_success = fields.BooleanField(description="是否成功", db_index=True)
    failure_reason = fields.CharField(max_length=200, null=True, description="失败原因")
    login_at = fields.DatetimeField(description="登录时间", db_index=True)
    logout_at = fields.DatetimeField(null=True, description="登出时间")
    description = fields.TextField(null=True, description="描述")

    # 外键关系
    user = fields.ForeignKeyField(
        "models.User", related_name="login_logs", description="关联用户", on_delete=fields.SET_NULL, null=True
    )

    class Meta:  # type: ignore
        table = "sys_login_log"
        table_description = "登录日志表"

    def __str__(self) -> str:
        return f"LoginLog(user_id={self.user_id}, login_at={self.login_at})"  # type: ignore

    def to_dict(self, exclude_sensitive: bool = False) -> dict:
        """转换为字典"""
        data = super().to_dict(exclude_sensitive=exclude_sensitive)
        data.update(
            {
                "user_id": self.user_id,  # type: ignore
                "login_type": self.login_type,
                "ip_address": self.ip_address,
                "location": self.location,
                "device": self.device,
                "user_agent": self.user_agent,
                "is_success": self.is_success,
                "failure_reason": self.failure_reason,
                "login_at": self.login_at,
                "logout_at": self.logout_at,
                "description": self.description,
            }
        )
        return data
